﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using CapstoneWinPhone.Data;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Xml.Linq;
using System.IO;

namespace CapstoneWinPhone
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor

        public MainPage()
        {
            InitializeComponent();
            DataContext = App.ViewModel;
        }

        private void ToggleLoginField()
        {
            LoginButton.IsEnabled = password.IsEnabled = Username.IsEnabled = !Username.IsEnabled;
        }

        private void login_Click(object sender, RoutedEventArgs e)
        {
            Button login = sender as Button;
            string username = null, password = null;
            if (login != null)
            {
                username = Username.Text;
                password = this.password.Password;
            }

            loginInfo.Text = "Logging in...";

            ToggleLoginField();
            DataHolder._currentUser = DataHolder.getUser(username, password);
            if (DataHolder._currentUser != null)
            {
                string uri = "http://workhelper.net/WorkHelperService.svc/getUser?username=" + username + "&password=" + password;
                try
                {
                    WebClient wClient = new WebClient();
                    wClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wClient_DownloadStringCompleted);
                    wClient.DownloadStringAsync(new Uri(uri, UriKind.Absolute));
                }
                catch (Exception ex)
                {
                    string s = ex.Message;
                }
            }
            
            if (DataHolder._currentUser == null && DataHolder.users.Where(u => u._username == username && u._password == password).FirstOrDefault() == null)
            {
                loginInfo.Text = "Invalid credentials";
            }
            else
            {
                if (DataHolder._currentMileageReport == null)
                {
                    NavigationService.Navigate(new Uri("/CreateMileageReportPage.xaml", UriKind.Relative));
                }
                if (DataHolder._currentExpenseLog == null)
                {
                    NavigationService.Navigate(new Uri("/CreateExpenseLogPage.xaml", UriKind.Relative));
                }
                NavigationService.Navigate(new Uri("/MainPivotPage.xaml", UriKind.Relative));
            }
            //App.ViewModel.WcfConnection.AttemptLoginAsync(username, password);
        }

        private void newUserButton_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/CreateANewUser.xaml", UriKind.Relative));
        }

        void wClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(e.Result));
                DataContractJsonSerializer jser = new DataContractJsonSerializer(typeof(CapstoneWinPhone.Abstract.User));
                Abstract.User user = (Abstract.User)jser.ReadObject(ms);
                ms.Close();
                XDocument doc = XDocument.Parse(user.information);
                var thisuser = from users in doc.Descendants("user")
                               select new User()
                               {
                                   _email = users.Descendants("_email").First().Value,
                                   _username = users.Descendants("_username").First().Value,
                                   _password = users.Descendants("password").First().Value
                               };
                DataHolder.users = thisuser.ToList();
            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }

        }
    }
}